import { Transaction, Category } from '../models/index.js';
import Joi from 'joi';
import { Op } from 'sequelize';

// 验证交易数据的Schema
const transactionSchema = Joi.object({
  type: Joi.string().valid('income', 'expense').required(),
  amount: Joi.number().positive().required(),
  categoryId: Joi.number().integer().positive().required(),
  description: Joi.string().max(200).allow(''),
  date: Joi.date().default(Date.now),
  account: Joi.string().valid('cash', 'bank_card', 'alipay', 'wechat', 'credit_card', 'other').default('cash'),
  isRecurring: Joi.boolean().default(false),
  recurringType: Joi.string().valid('daily', 'weekly', 'monthly', 'yearly').when('isRecurring', {
    is: true,
    then: Joi.required(),
    otherwise: Joi.optional()
  }),
  tags: Joi.array().items(Joi.string())
});

// 获取所有交易记录
export const getAllTransactions = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;
    
    // 构建查询条件
    const where = {};
    if (req.query.type) {
      where.type = req.query.type;
    }
    if (req.query.categoryId) {
      where.categoryId = req.query.categoryId;
    }
    if (req.query.startDate || req.query.endDate) {
      where.date = {};
      if (req.query.startDate) {
        where.date[Op.gte] = new Date(req.query.startDate);
      }
      if (req.query.endDate) {
        where.date[Op.lte] = new Date(req.query.endDate);
      }
    }

    const { rows: transactions, count: total } = await Transaction.findAndCountAll({
      where,
      include: [{
        model: Category,
        as: 'category',
        attributes: ['id', 'name', 'icon', 'color', 'type']
      }],
      order: [['date', 'DESC']],
      limit,
      offset
    });

    res.json({
      status: 'success',
      data: {
        transactions,
        pagination: {
          currentPage: page,
          totalPages: Math.ceil(total / limit),
          totalItems: total,
          itemsPerPage: limit
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '获取交易记录失败',
      error: error.message
    });
  }
};

// 获取单个交易记录
export const getTransactionById = async (req, res) => {
  try {
    const transaction = await Transaction.findByPk(req.params.id, {
      include: [{
        model: Category,
        as: 'category',
        attributes: ['id', 'name', 'icon', 'color', 'type']
      }]
    });

    if (!transaction) {
      return res.status(404).json({
        status: 'error',
        message: '交易记录不存在'
      });
    }

    res.json({
      status: 'success',
      data: { transaction }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '获取交易记录失败',
      error: error.message
    });
  }
};

// 创建新交易记录
export const createTransaction = async (req, res) => {
  try {
    // 验证数据
    const { error, value } = transactionSchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        status: 'error',
        message: '数据验证失败',
        details: error.details[0].message
      });
    }

    // 验证分类是否存在
    const category = await Category.findByPk(value.categoryId);
    if (!category) {
      return res.status(400).json({
        status: 'error',
        message: '指定的分类不存在'
      });
    }

    // 验证分类类型与交易类型是否匹配
    if (category.type !== value.type) {
      return res.status(400).json({
        status: 'error',
        message: '分类类型与交易类型不匹配'
      });
    }

    const transaction = await Transaction.create(value);

    // 返回完整的交易记录（包含分类信息）
    const populatedTransaction = await Transaction.findByPk(transaction.id, {
      include: [{
        model: Category,
        as: 'category',
        attributes: ['id', 'name', 'icon', 'color', 'type']
      }]
    });

    res.status(201).json({
      status: 'success',
      message: '交易记录创建成功',
      data: { transaction: populatedTransaction }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '创建交易记录失败',
      error: error.message
    });
  }
};

// 更新交易记录
export const updateTransaction = async (req, res) => {
  try {
    // 验证数据
    const { error, value } = transactionSchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        status: 'error',
        message: '数据验证失败',
        details: error.details[0].message
      });
    }

    // 验证分类是否存在
    if (value.categoryId) {
      const category = await Category.findByPk(value.categoryId);
      if (!category) {
        return res.status(400).json({
          status: 'error',
          message: '指定的分类不存在'
        });
      }

      // 验证分类类型与交易类型是否匹配
      if (category.type !== value.type) {
        return res.status(400).json({
          status: 'error',
          message: '分类类型与交易类型不匹配'
        });
      }
    }

    const [updatedRowsCount] = await Transaction.update(value, {
      where: { id: req.params.id },
      returning: true
    });

    if (updatedRowsCount === 0) {
      return res.status(404).json({
        status: 'error',
        message: '交易记录不存在'
      });
    }

    const transaction = await Transaction.findByPk(req.params.id, {
      include: [{
        model: Category,
        as: 'category',
        attributes: ['id', 'name', 'icon', 'color', 'type']
      }]
    });

    res.json({
      status: 'success',
      message: '交易记录更新成功',
      data: { transaction }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '更新交易记录失败',
      error: error.message
    });
  }
};

// 删除交易记录
export const deleteTransaction = async (req, res) => {
  try {
    const deletedRowsCount = await Transaction.destroy({
      where: { id: req.params.id }
    });

    if (deletedRowsCount === 0) {
      return res.status(404).json({
        status: 'error',
        message: '交易记录不存在'
      });
    }

    res.json({
      status: 'success',
      message: '交易记录删除成功'
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '删除交易记录失败',
      error: error.message
    });
  }
};